#!/bin/bash
# Copyright 2019 The Vitess Authors.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# git go vet pre-commit hook
#
# To use, store as .git/hooks/pre-commit inside your repository and make sure
# it has execute permissions.

if [ -z "$GOPATH" ]; then
  echo "ERROR: pre-commit hook for go vet: \$GOPATH is empty. Please run 'source dev.env' to set the correct \$GOPATH."
  exit 1
fi

# This script does not handle file names that contain spaces.
gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '^go/.*\.go$' | grep -v '^go/vt/proto/' | grep -v 'go/vt/sqlparser/sql.go')
if [ "$gofiles" = "" ]; then
  exit 0
fi

# xargs -n1 because dirname on MacOS does not support multiple arguments.
gopackages=$(echo $gofiles | xargs -n1 dirname | sort -u)

errors=

# If any checks are found to be useless, they can be disabled here.
# See the output of "go doc cmd/vet" for a list of flags.
vetflags=""

# Run on one package at a time
for gopackage in $gopackages
do
    if ! go vet $vetflags "vitess.io/vitess/$gopackage" 2>&1; then
        errors=YES
    fi
done

[ -z "$errors" ] && exit 0

echo
echo "Please fix the go vet warnings above. To disable certain checks, change vetflags in misc/git/hooks/govet."
exit 1

